package com.qsw.crashcollectionlib.core;

import android.text.TextUtils;
import android.util.Log;

import com.qsw.crashcollectionlib.bean.ExceptionMessage;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

/**
 * 日志文件的真正读写控制类
 */
class LogFileController {
    private static final String TAG = "LogFileController";

    /**
     * 向日志中写入一个异常信息
     *
     * @param em
     */
    public void saveException2Log(ExceptionMessage em) {
        Throwable ex = em.getException();
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(em.getOtherMessage())) {
            sb.append(em.getOtherMessage() + "\n");
        } else if (ex == null) {
            sb.append("程序崩溃但未收集到异常...");
        }
        if (ex != null) {
            // 写入异常名
            sb.append(ex.getClass().getCanonicalName() + " :  ");
            // 写入异常信息
            sb.append(ex.getMessage() + "\n");
            StackTraceElement[] stackTrace = ex.getStackTrace();
            // 写入异常方法调用栈
            for (StackTraceElement stackTraceElement : stackTrace) {
                sb.append("\t" + stackTraceElement.toString() + "\n");
            }
        }
        FileWriter fw = null;
        try {
            File filePath = new File(em.getLogPath());
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            File file = new File(filePath, em.getLogName());
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file, true);
            // 写入异常抛出时间
            Date date = new Date(em.getThrowTime());
            if (em.isSimpleSave()) {
                fw.write(String.format("%tF  %tT.%tL : ", date, date, date));
            } else {
                fw.write(String.format("%tF  %tT.%tL\n", date, date, date));
            }
            // 写入异常内容
            fw.write(sb.toString());
            if (!em.isSimpleSave()) {
                fw.write("\n**********************************************************************************************************************\n\n");
            }
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
